﻿using Homework12.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Homework12.Controllers
{
    public class OrderController : ApiController
    {
        Product[] products = new Product[]
       {
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
       };
        
        public static List<Order> Orders = new List<Order>()
        {
            new Order(new Customer("hyy"),new List<OrderItem> { new OrderItem(new Goods("apple",3), 1) }),
            new Order(new Customer("hbb"),new List<OrderItem> { new OrderItem(new Goods("pear",5), 1) }),
        };

        [HttpGet]
        public IEnumerable<Order> GetAllOrders()
        {
            return Orders;
        }

       [HttpGet]
        public Order InquiryOrderByID(int id)
        {
            var order = Orders.FirstOrDefault((od) => od.OrderID == id);
            if (order == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);
            return order;
            
        }

        [HttpPost]
        public void AddOrder(dynamic obj)
        {
           string customer = obj.customer;
            string goodsName = obj.goodsname;
            double price = obj.goodsUnitPrice;
            int num = obj.goodsNum;
            Order order = new Order(new Customer(customer),
                new List<OrderItem> { new OrderItem(new Goods(goodsName, price), num)});
            Orders.Add(order);
        }

        [HttpDelete]
        public void DeleteOrder(int id)
        {
            var orders = Orders
                           .Where(od => od.OrderID == id);
            Orders.Remove(orders.ElementAt(0));
        }

        [HttpPut]
        public void ReviseOrderByClient(int num, string clientName)
        {
            var orders = Orders
                           .Where(od => od.OrderID == num);
            orders.ElementAt(0).Customer = new Customer(clientName);
        }
        

    }
}
